from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import Select
from selenium.common.exceptions import NoSuchElementException
import unittest, time, re

class UserManagement(unittest.TestCase):
    def setUp(self):
        self.driver = webdriver.Firefox()
        self.driver.implicitly_wait(30)
        self.base_url = "http://localhost:8080/"
        self.verificationErrors = []
        self.accept_next_alert = True
    
    def test_create_user(self):
        driver = self.driver
        driver.get(self.base_url + "/php4dvd/")
        driver.find_element_by_id("username").clear()
        driver.find_element_by_id("username").send_keys("admin")
        driver.find_element_by_name("password").clear()
        driver.find_element_by_name("password").send_keys("admin")
        driver.find_element_by_name("submit").click()
        driver.find_element_by_link_text("User management").click()
        driver.find_element_by_id("username").clear()
        driver.find_element_by_id("username").send_keys("Pavel")
        driver.find_element_by_name("email").clear()
        driver.find_element_by_name("email").send_keys("pavel@gog.com")
        driver.find_element_by_id("password").clear()
        driver.find_element_by_id("password").send_keys("q1w2e3r4t5")
        driver.find_element_by_id("password2").clear()
        driver.find_element_by_id("password2").send_keys("q1w2e3r4t5")
        Select(driver.find_element_by_name("permission")).select_by_visible_text("Editor")
        driver.find_element_by_name("submit").click()
        driver.find_element_by_link_text("Pavel").click()
        driver.find_element_by_link_text("Log out").click()
        self.assertRegexpMatches(self.close_alert_and_get_its_text(), r"^Are you sure you want to log out[\s\S]$")

    
    def is_element_present(self, how, what):
        try: self.driver.find_element(by=how, value=what)
        except NoSuchElementException, e: return False
        return True
    
    def close_alert_and_get_its_text(self):
        try:
            alert = self.driver.switch_to_alert()
            text = alert.text
            if self.accept_next_alert:
                alert.accept()
            else:
                alert.dismiss()
            return text
        finally: self.accept_next_alert = True
    
    def tearDown(self):
        self.driver.quit()
        self.assertEqual([], self.verificationErrors)

if __name__ == "__main__":
    unittest.main()